const customerModel = require('../models/customerModel');
const request = require('request');


const create = async(ctx, next) => {
    const req = ctx.request.body;
    const data = Object.assign({ status: 0, createDate: new Date() }, req);
    const result = await customerModel.create(data);
    if (result) {
        ctx.body = {
            code: 1,
            msg: '添加成功！',
            data: result
        };
    }
}

const findById = async(ctx, next) => {
    const id = ctx.params.id;
    const result = await customerModel.findById(id);
    if (result) {
        ctx.body = {
            code: 1,
            data: result
        };
    }
}

const find = async(ctx, next) => {
    const query = ctx.request.query;
    const name = query.name;
    const condition = {
        status: {
            $gt: -1
        }
    };
    if (name) {
        condition.name = {
            $regex: name
        }
    }
    const result = await customerModel.find(condition, null, {
        sort: {
            createDate: 'desc'
        }
    });
    if (result) {
        ctx.body = {
            code: 1,
            data: result
        };
    }
}

const update = async(ctx, next) => {
    const req = ctx.request.body;
    const result = await customerModel.update({
        _id: req._id
    }, req);
    if (result) {
        ctx.body = {
            code: 1,
            msg: '修改成功！',
            data: {}
        };
    }
}

module.exports = {
    create,
    find,
    update,
    findById
};